/* eslint-disable @typescript-eslint/no-use-before-define */
import DictTag from "@/components/DictTag";
import ExportModal from "@/components/ExportModal";
import downLoad from "@/utils/download";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import {
	Avatar,
	Card,
	Col,
	Divider,
	Dropdown,
	FormInstance,
	Input,
	MenuProps,
	Modal,
	Popconfirm,
	Row,
	Space,
	Switch,
	Typography,
	message
} from "antd";
import React, { useEffect, useRef, useState } from "react";
import AuthRoleForm from "./components/AuthRoleForm";
import ResetPasswordForm, { FormValueType } from "./components/ResetPwd";
// import UserModalForm from "./components/UserModalForm";
import DeptTreeList from "./components/deptTreeList";
import UserForm, { UserFormData } from "./components/userForm";
// import ResetPwd from './components/ResetPwd';
// import UpdateForm from './edit';
import CustomerTable from "@/components/CustomerTable";
import { getDict } from "@/services/api/module/system/dict";
import { optionSelecet } from "@/services/api/module/system/post";
import { getList } from "@/services/api/module/system/dept";
import { getPageList, remove, restPassword, save, update, changeStatus as updateStatus } from "@/services/api/module/system/user";
import FilterDrawer from "@/components/FilterDrawer";
const { confirm } = Modal;
import UserDetails from "./components/UserDetails";
import { createTableColumns, pagination } from "./constants";
const UserTableList: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [modalVisible, setModalVisible] = useState<boolean>(false);
	const [authRoleModalVisible, setAuthRoleModalVisible] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentRowId, setCurrentRowId] = useState<number | undefined>();
	const [currentUserId, setCurrentUserId] = useState<number | undefined>();
	const [selectedRows, setSelectedRows] = useState<any>([]);
	const [selectOrg, setSelectOrg] = useState<any>({ id: 0 });
	const [selectDeptId, setDeptSelectId] = useState<any>();
	const [sexOptions, setSexOptions] = useState<any>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [roleIds, setRoleIds] = useState<number[]>();
	const [deptTree, setDeptTree] = useState<any>();
	const [, setPostOptions] = useState<any>([]);
	const [resetFormOpen, setResetFormOpen] = useState<boolean>(false);
	const [exportOpen, setExportOpen] = useState<boolean>(false);
	const [resetPasswordTypes, setResetPasswordTypes] = useState<any>([]);
	const [userDetailTitle, setUserDetailTitle] = useState<string>("用户信息");
	const [userDetailOpen, setUserDetailOpen] = useState<boolean>(false);
	const [useTypOptions, setUserTypeOptions] = useState<any>([]);
	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	useEffect(() => {
		getDict("sys_user_sex").then(data => {
			setSexOptions(data);
		});
		getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		getDict("sys_builtin_password").then(data => {
			setResetPasswordTypes(data);
		});
		getDict("sys_user_type").then(data => {
			setUserTypeOptions(data);
		});
		getTreeData();
	}, []);
	// 部门数据
	const getTreeData = () => {
		getList().then((res: any) => {
			setDeptTree(res.data);
		});
	};

	// 重置密码
	const resetPassword = async (values: FormValueType) => {
		return await new Promise<void>((resolve, reject) => {
			restPassword(values)
				.then((res: any) => {
					message.success(res?.msg);
					setResetFormOpen(false);
					setCurrentUserId(undefined);
					resolve();
				})
				.catch(error => {
					reject(error);
				});
		});
	};
	const handleColumnEditor = (record: API.Setting.UserVo) => {
		setModalVisible(true);
		setCurrentRowId(record.id);
	};
	const handleColumnRemove = (record: API.Setting.UserVo) => {
		handleRemove(record.id);
	};
	const handleColumnRealName = (record: API.Setting.UserVo) => {
		setCurrentRowId(record.id);
		setUserDetailOpen(true);
		setUserDetailTitle(`用户信息·${record?.realName}`);
	};

	const handleColumnDetails = (record: API.Setting.UserVo) => {
		setCurrentRowId(record.id);
		setUserDetailOpen(true);
		setUserDetailTitle(`用户信息·${record?.realName}`);
	};
	const handleDropdownClick = (key: string, record: API.Setting.UserVo) => {
		switch (key) {
			case "restPassword":
				setResetFormOpen(true);
				setCurrentUserId(record?.id);
				break;
			case "authRole":
				setAuthRoleModalVisible(true);
				setCurrentRowId(record?.id);
				break;
		}
	};

	// 列表字段
	const columns: ProColumns<API.Setting.UserVo>[] = createTableColumns(
		statusOptions,
		sexOptions,
		handleColumnEditor,
		handleColumnRemove,
		handleColumnRealName,
		handleColumnDetails,
		handleDropdownClick
	);

	// 修改角色状态
	const changeStatus = (values: API.System.UserVo) => {
		const newStatus = values.status === "0" ? "1" : "0";
		const text = values.status === "1" ? "启用" : "停用";
		confirm({
			title: `提示`,
			content: `确认要${text}，${values.userName}用户吗？`,
			okText: "确认",
			cancelText: "取消",
			async onOk() {
				try {
					return await new Promise<void>((resolve, reject) => {
						updateStatus({
							id: values.id,
							status: newStatus
						})
							.then((res: any) => {
								message.success(res?.msg);
								actionRef.current?.reload();
								resolve();
							})
							.catch(() => {
								reject();
							});
					});
				} catch {
					return console.log("Oops errors!");
				}
			}
		});
	};

	// 保存
	const handleSave = async (values: UserFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as UserFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 编辑
	const handleUpdate = async (values: UserFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as UserFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 删除
	const handleRemove = async (id: number | Array<number>) => {
		return new Promise((reslove, reject) => {
			remove(id)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setModalVisible(false);
		setCurrentRowId(undefined);
		if (actionRef.current) {
			actionRef.current.reload();
		}
	};

	//导出
	const handleExport = async (values: any) => {
		const downLoadParams = {
			...values,
			...formTableRef?.current?.getFieldsValue(),
			current: actionRef?.current?.pageInfo?.current,
			pageSize: actionRef?.current?.pageInfo?.pageSize
		};
		return new Promise<void>(reslove => {
			downLoad.export("/system/user/export", downLoadParams);
			reslove();
		});
	};

	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue, ...{ deptId: selectDeptId } }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			userName: value
		});
		actionRef.current?.reload();
	};

	return (
		<>
			<Row gutter={10}>
				<Col lg={24} xl={5} md={24} xs={24}>
					<Card style={{ height: "calc(100vh - 55px - 47px - 16px)" }} title={null}>
						<DeptTreeList
							treeData={deptTree}
							onSelect={async (value: any) => {
								setDeptSelectId(value.id);
								if (actionRef.current) {
									actionRef.current?.reload();
								}
							}}
						/>
					</Card>
				</Col>
				<Col lg={24} xl={19} md={24} xs={24}>
					<CustomerTable<API.System.UserVo>
						actionRef={actionRef}
						tableStyle={{ minHeight: "calc(100vh - 240px)" }}
						formRef={formTableRef}
						rowKey="id"
						key="userList"
						size="small"
						tableAlertRender={false}
						search={false}
						toolbar={{
							search: (
								<Space>
									<Input.Search placeholder="通过用户账号搜索" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
									<FilterDrawer
										columns={columns}
										tableActionRef={actionRef}
										onReset={() => {
											setSearchFormValue(undefined);
											actionRef?.current?.reload();
										}}
										onSubmit={(values: any) => {
											setSearchFormValue(values);
											actionRef?.current?.reload();
										}}
									/>
								</Space>
							)
						}}
						columns={columns}
						pagination={pagination}
						request={tableDataRequest}
						rowSelection={{
							onChange: (_, selectedRows) => {
								setSelectedRows(selectedRows);
							},
							getCheckboxProps: (record: any) => ({
								disabled: record?.id === 1, // Column configuration not to be checked
								name: record.id
							})
						}}
					/>
				</Col>
			</Row>
			<UserForm
				onSubmit={async (values: UserFormData) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				onCancel={() => {
					setModalVisible(false);
					setCurrentRowId(undefined);
				}}
				open={modalVisible}
				id={currentRowId}
				sexOptions={sexOptions}
				statusOptions={statusOptions}
				depts={deptTree || []}
			/>
			<AuthRoleForm
				userId={currentRowId}
				// idValue={currentId}
				onCancel={() => {
					setAuthRoleModalVisible(false);
					setSelectedRows([]);
					// setCurrentRow(undefined);
				}}
				open={authRoleModalVisible}
				roleIds={roleIds || []}
			/>
			<ExportModal
				onCancel={() => {
					setExportOpen(false);
				}}
				onSubmit={handleExport}
				title="导出用户信息"
				open={exportOpen}
				columns={columns}
			/>
			<ResetPasswordForm
				open={resetFormOpen}
				userId={currentUserId}
				types={resetPasswordTypes}
				onSubmit={async (values: FormValueType) => {
					return await resetPassword(values);
				}}
				onCancel={() => {
					setResetFormOpen(false);
					setCurrentRowId(undefined);
				}}
			/>
			<UserDetails
				open={userDetailOpen}
				currentId={currentRowId}
				title={userDetailTitle}
				onClose={() => {
					setCurrentRowId(undefined);
					setUserDetailOpen(false);
				}}
				sexOptions={sexOptions}
				statusOptions={statusOptions}
				useType={useTypOptions}
			/>
			{/* <ResetPwd
        onSubmit={async (values: any) => {
          const success = await resetUserPwd(values.userId, values.password);
          if (success) {
            setResetPwdModalVisible(false);
            setSelectedRows([]);
            setCurrentRow(undefined);
            message.success('密码重置成功。');
          }
        }}
        onCancel={() => {
          setResetPwdModalVisible(false);
          setSelectedRows([]);
          setCurrentRow(undefined);
        }}
        open={resetPwdModalVisible}
        values={currentRow || {}}
      /> */}
			{/* <UserForm
        onSubmit={async (values) => {
          let success = false;
          if (values.userId) {
            success = await handleUpdate({ ...values } as API.System.User);
          } else {
            success = await handleAdd({ ...values } as API.System.User);
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
        sexOptions={sexOptions}
        statusOptions={statusOptions}
        posts={postList || []}
        postIds={postIds || []}
        roles={roleList || []}
        roleIds={roleIds || []}
        depts={deptTree || []}
      />
      <ResetPwd
        onSubmit={async (values: any) => {
          const success = await resetUserPwd(values.userId, values.password);
          if (success) {
            setResetPwdModalVisible(false);
            setSelectedRows([]);
            setCurrentRow(undefined);
            message.success('密码重置成功。');
          }
        }}
        onCancel={() => {
          setResetPwdModalVisible(false);
          setSelectedRows([]);
          setCurrentRow(undefined);
        }}
        open={resetPwdModalVisible}
        values={currentRow || {}}
      />
      <AuthRoleForm
        onSubmit={async (values: any) => {
          const success = await updateAuthRole(values);
          if (success) {
            setAuthRoleModalVisible(false);
            setSelectedRows([]);
            setCurrentRow(undefined);
            message.success('配置成功。');
          }
        }}
        onCancel={() => {
          setAuthRoleModalVisible(false);
          setSelectedRows([]);
          setCurrentRow(undefined);
        }}
        open={authRoleModalVisible}
        roles={roleList || []}
        roleIds={roleIds || []}
      /> */}
			{/* <UserModalForm /> */}
		</>
	);
};

export default UserTableList;
